package com.example.service.impl;

import com.example.model.CargoRequest;
import com.example.model.DeckRequest;
import com.example.model.ReponseResult;
import com.example.model.Result;
import com.example.service.Compute;
import com.example.session.LoadSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class LoadSessionServiceimpl {
    @Autowired
    private Compute compute;
    private final Map<String, LoadSession> sessions = new ConcurrentHashMap<>();

    /** 1. 新建会话 */
    public String createSession() {
        String id = UUID.randomUUID().toString();
        LoadSession s = new LoadSession();
        s.setSessionId(id);
        sessions.put(id, s);
        return id;
    }

    /** 2. 保存货物列表 */
    public Result saveCargo(String sessionId, List<CargoRequest> cargos) {
        // 检查会话是否存在
        LoadSession s = sessions.get(sessionId);
        if (s == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Session 不存在：" + sessionId);
        }
        //  会话存在保存货物信息
        s.setCargos(cargos);
        return Result.success("已成功接收货物信息");
    }

    /** 3. 保存甲板并执行排载，返回装载结果 */
    public ReponseResult saveDeckAndLoad(
            String sessionId,
            DeckRequest deck
    ) {
        LoadSession s = sessions.get(sessionId);
        if (s == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Session 不存在：" + sessionId);
        }
        if (s.getCargos() == null) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "请先上传货物信息");
        }
        s.setDeck(deck);

        // 调用排载算法，生成 ReponseResult
        ReponseResult plan = compute.computePlan(deck, s.getCargos());
        // 清理会话
        sessions.remove(sessionId);

        return plan;
    }
}
